﻿using System;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using Quizz.Infrastructure;
using Quizz.Library.QuizzServiceReference;
using Quizz.Library.Security;

namespace Quizz.Library.Helper
{
    public sealed class AccessFactory
    {
        #region Fields
        
        #endregion

        #region Properties

        public static HttpSessionState Session
        {
            get { return HttpContext.Current.Session; }
        }

        public static User CurrentUser
        {
            get { return Session[Constants.USER_LOGINED] as User; }
            set { Session[Constants.USER_LOGINED] = value; }
        }

        public static string AvartarFolder
        {
            get
            {
                var configPath = ConfigurationManager.AppSettings["DataFolder"];
                if (string.IsNullOrEmpty(configPath))
                    throw new ConfigurationErrorsException("DataFolder does not configurated.");
                return HttpContext.Current.Request.MapPath(configPath) + "Avatar/";
            }
        }

        public static string AvartarUrl
        {
            get {
                var configPath = ConfigurationManager.AppSettings["DataFolder"];
                if (string.IsNullOrEmpty(configPath))
                    throw new ConfigurationErrorsException("DataFolder does not configurated.");
                return VirtualPathUtility.ToAbsolute(configPath + "Avartar/");
            }
        }

        public static string DefaultAvatar
        {
            get { return AvartarUrl + "anonymous.png"; }
        }

        public static string ServerName
        {
            get { return HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; }
        }

        public static int ServerPort{
            get { return int.Parse(HttpContext.Current.Request.ServerVariables["SERVER_PORT"]); }
        }

        public static string FullServerHost {
            get {
                return HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
            }
        }

        public static Cache Cache
        {
            get { return HttpContext.Current.Cache; }
        }

        public static int MaxLoginFailCount
        {
            get {
                var configCount = ConfigurationManager.AppSettings["MaxLoginFailCount"];
                if (string.IsNullOrWhiteSpace(configCount))
                    throw new ConfigurationErrorsException("MaxLoginFailCount in AppSettings is not specified !");
                return int.Parse(configCount);
            }
        }

        public static int LoginFailLockTimeout
        {
            get {
                var configValue = ConfigurationManager.AppSettings["LoginFailLockTimeout"];
                if (string.IsNullOrWhiteSpace(configValue))
                    throw new ConfigurationErrorsException("LoginFailLockTimeout in AppSettings is not specified !");
                return int.Parse(configValue);
            }
        }

        #endregion

        #region Methods

        public static void RemoveCurrentUser()
        {
            Session.Remove(Constants.USER_LOGINED);
        }

        public static void Login(User user)
        {
            Session[Constants.USER_LOGINED] = user;
            var loginLog = new LoginLog
                               {
                                   IsOnline = true,
                                   LoginTime = DateTime.Now,
                                   SessionId = Session.SessionID,
                                   UserId = user.Id
                               };
            using(var proxy = new QuizzProjectServiceClient())
            {
                proxy.LoginLogInsert(loginLog);
            }
        }

        public static void Logout()
        {
            Session[Constants.USER_LOGINED] = null;
            Session.Abandon();
        }

        public static string RandomPassword(int length)
        {
            return System.Web.Security.Membership.GeneratePassword(length, 4);
        }

        public static string EncodePassword(string clearPass)
        {
            return Hash.GetHash(clearPass, Hash.HashType.SHA256);
        }

        public static bool IsUserLogined()
        {
            return Session[Constants.USER_LOGINED] != null;
        }

        public static bool IsAdminLogined()
        {
            return IsUserLogined() && CurrentUser.RoleId == Constants.ADMIN_ROLE_ID;
        }

        public static bool IsEditorLogined()
        {
            return IsUserLogined() &&
                (CurrentUser.RoleId == Constants.EDITOR_ROLE_ID ||
                CurrentUser.RoleId == Constants.ADMIN_ROLE_ID);
        }

        public static string MapServerPath(string relativePath)
        {
            return HttpContext.Current.Request.MapPath(relativePath);
        }

        #endregion
    }
}
